/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hvkdbmc.setting;

import hvkdbmc.entities.HVKColumnInfo;
import hvkdbmc.entities.HVKTableInfo;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author LuckyMan
 */
public class HVKBaseUtils {

    public static String MakeDaoFileFromTable(HVKTableInfo tableInfo) {
        if (tableInfo == null || tableInfo.name == null || tableInfo.name.trim().equals("")) {
            return "-0: Object table is null. Please check the object.";
        }
        HVKLogManager.WriteLogAcction("Begin create DAO file for table :" + tableInfo.name + "...");
        String mess = "";
        if (HVKSetting.daoRootFolder.endsWith("\\") || HVKSetting.daoRootFolder.endsWith("/")) {
            HVKSetting.daoRootFolder = HVKSetting.daoRootFolder.substring(0, HVKSetting.daoRootFolder.length() - 1);
        }
//        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + "\\" + tableInfo.getTableClassName() + ".java";

//        String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));

       String filePath = HVKSetting.daoRootFolder.trim() + "\\" + tableInfo.getTableClassName() + HVKSetting.suffixDao + ".java";

        File fileToWrite = new File(filePath);
        if (fileToWrite.exists()) {
            HVKLogManager.WriteError("-1: File " + filePath + " existed. Can't not replacae file.", HVKBaseUtils.class.getName(), "MakeDaoFileFromTable");
            mess = "-1: File " + filePath + " existed. Can't not replacae file.";
        } else {
            String body = makeDaoBodyFromTable(tableInfo);
            try {
                WriteToFile(filePath, body);
                mess = "ok: File " + filePath + " created successful!";
            } catch (Exception ex) {
                HVKLogManager.WriteError(ex.getMessage(), HVKBaseUtils.class.getName(), "MakeDaoFileFromTable");
                mess = "-1: File " + filePath + " existed." + ex.getMessage();
            }
        }
        HVKLogManager.WriteLogAcction("Finished create DAO file for table : " + tableInfo.name + " .Result : " + mess);
        return mess;
    }

    public static String MakeIbatisDaoFileFromTable(HVKTableInfo tableInfo) {
        if (tableInfo == null || tableInfo.name == null || tableInfo.name.trim().equals("")) {
            return "-0: Object table is null. Please check the object.";
        }
        HVKLogManager.WriteLogAcction("Begin create IBASTIS DAO file for table :" + tableInfo.name + "...");
        String mess = "";
        if (HVKSetting.daoRootFolder.endsWith("\\") || HVKSetting.daoRootFolder.endsWith("/")) {
            HVKSetting.daoRootFolder = HVKSetting.daoRootFolder.substring(0, HVKSetting.daoRootFolder.length() - 1);
        }
//        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + "\\" + tableInfo.getTableClassName() + ".java";

//        String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));

        String filePath = HVKSetting.daoRootFolder.trim() + "\\" + tableInfo.getTableClassName() + HVKSetting.suffixIbatisDao + ".java";

        File fileToWrite = new File(filePath);
        if (fileToWrite.exists()) {
            HVKLogManager.WriteError("-1: File " + filePath + " existed. Can't not replacae file.", HVKBaseUtils.class.getName(), "MakeIbatisDaoFileFromTable");
            mess = "-1: File " + filePath + " existed. Can't not replacae file.";
        } else {
            String body = makeIbatisDaoBodyFormTable(tableInfo);
            try {
                WriteToFile(filePath, body);
                mess = "ok: File " + filePath + " created successful!";
            } catch (Exception ex) {
                HVKLogManager.WriteError(ex.getMessage(), HVKBaseUtils.class.getName(), "MakeIbatisDaoFileFromTable");
                mess = "-1: File " + filePath + " existed." + ex.getMessage();
            }
        }
        HVKLogManager.WriteLogAcction("Finished create IBATIS DAO file for table : " + tableInfo.name + " .Result : " + mess);
        return mess;
    }
    
     public static String MakeServiceFileFromTable(HVKTableInfo tableInfo) {
        if (tableInfo == null || tableInfo.name == null || tableInfo.name.trim().equals("")) {
            return "-0: Object table is null. Please check the object.";
        }
        HVKLogManager.WriteLogAcction("Begin create IBASTIS DAO file for table :" + tableInfo.name + "...");
        String mess = "";
        if (HVKSetting.serviceRootFolder.endsWith("\\") || HVKSetting.serviceRootFolder.endsWith("/")) {
            HVKSetting.serviceRootFolder = HVKSetting.serviceRootFolder.substring(0, HVKSetting.serviceRootFolder.length() - 1);
        }
//        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + "\\" + tableInfo.getTableClassName() + ".java";

//        String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));

        String filePath = HVKSetting.serviceRootFolder.trim() + "\\" + tableInfo.getTableClassName() + HVKSetting.suffixService + ".java";

        File fileToWrite = new File(filePath);
        if (fileToWrite.exists()) {
            HVKLogManager.WriteError("-1: File " + filePath + " existed. Can't not replacae file.", HVKBaseUtils.class.getName(), "MakeServiceFileFromTable");
            mess = "-1: File " + filePath + " existed. Can't not replacae file.";
        } else {
            String body = makeServiceBodyFromTable(tableInfo);
            try {
                WriteToFile(filePath, body);
                mess = "ok: File " + filePath + " created successful!";
            } catch (Exception ex) {
                HVKLogManager.WriteError(ex.getMessage(), HVKBaseUtils.class.getName(), "MakeServiceFileFromTable");
                mess = "-1: File " + filePath + " existed." + ex.getMessage();
            }
        }
        HVKLogManager.WriteLogAcction("Finished create SERVICE file for table : " + tableInfo.name + " .Result : " + mess);
        return mess;
    }
     
          public static String MakeDaoServiceFileFromTable(HVKTableInfo tableInfo) {
        if (tableInfo == null || tableInfo.name == null || tableInfo.name.trim().equals("")) {
            return "-0: Object table is null. Please check the object.";
        }
        HVKLogManager.WriteLogAcction("Begin create IBASTIS DAO file for table :" + tableInfo.name + "...");
        String mess = "";
        if (HVKSetting.serviceRootFolder.endsWith("\\") || HVKSetting.serviceRootFolder.endsWith("/")) {
            HVKSetting.serviceRootFolder = HVKSetting.serviceRootFolder.substring(0, HVKSetting.serviceRootFolder.length() - 1);
        }
//        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + "\\" + tableInfo.getTableClassName() + ".java";

//        String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));

        String filePath = HVKSetting.serviceRootFolder.trim() + "\\" + tableInfo.getTableClassName() + HVKSetting.suffixDaoService + ".java";

        File fileToWrite = new File(filePath);
        if (fileToWrite.exists()) {
            HVKLogManager.WriteError("-1: File " + filePath + " existed. Can't not replacae file.", HVKBaseUtils.class.getName(), "MakeDaoServiceFileFromTable");
            mess = "-1: File " + filePath + " existed. Can't not replacae file.";
        } else {
            String body = makeDaoServiceBodyFormTable(tableInfo);
            try {
                WriteToFile(filePath, body);
                mess = "ok: File " + filePath + " created successful!";
            } catch (Exception ex) {
                HVKLogManager.WriteError(ex.getMessage(), HVKBaseUtils.class.getName(), "MakeDaoServiceFileFromTable");
                mess = "-1: File " + filePath + " existed." + ex.getMessage();
            }
        }
        HVKLogManager.WriteLogAcction("Finished create DAO SERVICE file for table : " + tableInfo.name + " .Result : " + mess);
        return mess;
    }
    

    public static String makeDaoBodyFromTable(HVKTableInfo tableInfo) {
        String modelFileName = HVKSetting.modelMapRootPackage.trim().toLowerCase() + "." + tableInfo.getTableClassName() + HVKSetting.suffixModel;
        String modelName = tableInfo.getTableClassName() + HVKSetting.suffixModel;
//        String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));
        String result = "package "+HVKSetting.daoPackage+";";
        result += "\nimport java.sql.SQLException;";
        result += "\nimport java.util.List;";
        result += "\nimport " + modelFileName + ";";
        result += "\npublic interface " + tableInfo.getTableClassName()+HVKSetting.suffixDao;
        result += "\n{";
        //Insert statement
        result += "\npublic Long insert(" + modelName + " fileName) throws SQLException;";
        result += "\npublic int update(" + modelName + " keyObject)throws Exception;";
        result += "\npublic int delete(Long keyID)throws Exception;";
        result += "\npublic List selectAll" + tableInfo.getTableClassName() + "()throws Exception;";
        result += "\npublic " + modelName + " select" + tableInfo.getTableClassName() + "ByID(Long " + "keyVal" + ") throws Exception;";
        result += "\n}";
        return result;
    }
    
        public static String makeServiceBodyFromTable(HVKTableInfo tableInfo) {
        String modelFileName = HVKSetting.modelMapRootPackage.trim().toLowerCase() + "." + tableInfo.getTableClassName() + HVKSetting.suffixModel;
         String modelName = tableInfo.getTableClassName() + HVKSetting.suffixModel;
        //String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));
        String result = "package "+HVKSetting.servicepackage+";";
        result += "\nimport java.sql.SQLException;";
        result += "\nimport java.util.List;";
        result += "\nimport " + modelFileName + ";";
        result += "\npublic interface " + tableInfo.getTableClassName()+HVKSetting.suffixService;
        result += "\n{";
        //Insert statement
        result += "\npublic Long insert(" + modelName + " object) throws SQLException;";
        result += "\npublic int update(" + modelName + " object)throws Exception;";
        result += "\npublic int delete(Long keyID)throws Exception;";
        result += "\npublic List selectAll" + tableInfo.getTableClassName() + "()throws Exception;";
        result += "\npublic " + modelName + " select" + tableInfo.getTableClassName() + "ByID(Long " + "keyVal" + ") throws Exception;";
        result += "\n}";
        return result;
    }
    
    

    public static String makeIbatisDaoBodyFormTable(HVKTableInfo tableInfo) {
        String modelFileName = HVKSetting.modelMapRootPackage.trim().toLowerCase() + "." + tableInfo.getTableClassName() + HVKSetting.suffixModel;
        String ibatisClassName = tableInfo.getTableClassName() + HVKSetting.suffixIbatisDao;
        String daoName = tableInfo.getTableClassName() + HVKSetting.suffixDao;
        String modelName = tableInfo.getTableClassName() + HVKSetting.suffixModel;
        String mapNameSpace = HVKSetting.prefixNamespaceXMLMap + tableInfo.getTableClassName();
        String result = "package "+HVKSetting.daoPackage+";"
                + "\nimport java.sql.SQLException;"
                + "\nimport java.util.List;"
                + "\nimport org.springframework.orm.ibatis.SqlMapClientTemplate;"
                + "\nimport " + modelFileName + ";";

        result += "\npublic class " + ibatisClassName + " extends SqlMapClientTemplate implements " + daoName + "{"
                + "\n@Override"
                + "\npublic java.lang.Long insert(" + modelName + " object) throws SQLException"
                + "\n{"
                + "\n    Long ret= (Long) queryForObject(\"" + mapNameSpace + ".insert" + tableInfo.getTableClassName() + "\", object);"
                + "\n    return ret;"
                + "\n}"
                + "\n@Override"
                + "\npublic int update(" + modelName + " object) throws Exception {"
                + "\n    int ret= update(\"" + mapNameSpace + ".update" + tableInfo.getTableClassName() + "\" ,object);"
                + "\n    return ret;"
                + "\n}"
                + "\n@Override"
                + "\npublic int delete(Long keyVal) throws Exception {"
                + "\nint ret= delete(\"" + mapNameSpace + ".delete" + tableInfo.getTableClassName() + "\",keyVal);"
                + "\n    return ret;"
                + "\n}"
                + "\n@Override"
                + "\npublic List selectAll" + tableInfo.getTableClassName() + "() throws Exception {"
                + "\n    List ret= queryForList(\"" + mapNameSpace + ".selectAll" + tableInfo.getTableClassName() + "\",null);"
                + "\n    return ret;"
                + "\n}"
                + "\n@Override"
                + "\npublic " + modelName + " select" + tableInfo.getTableClassName() + "ByID(Long keyVal) throws Exception {"
                + "\n    " + modelName + " model= ("+modelName+") queryForObject(\"" + mapNameSpace + ".select" + tableInfo.getTableClassName() + "ByID\", keyVal);"
                + "\n    return model;"
                + "\n}"
                + "}";

        return result;
    }

        public static String makeDaoServiceBodyFormTable(HVKTableInfo tableInfo) {
        String modelFileName = HVKSetting.modelMapRootPackage.trim().toLowerCase() + "." + tableInfo.getTableClassName() + HVKSetting.suffixModel;
        String daoServiceClassName = tableInfo.getTableClassName() + HVKSetting.suffixDaoService;
        String daoName = tableInfo.getTableClassName() + HVKSetting.suffixDao;
        
        String serviceName = tableInfo.getTableClassName() + HVKSetting.suffixService;
        String modelName = tableInfo.getTableClassName() + HVKSetting.suffixModel;
        String result = "package "+HVKSetting.servicepackage+";"
                + "\nimport java.sql.SQLException;"
                + "\nimport java.util.List;"
                + "\nimport "+HVKSetting.daoPackage+"."+daoName+";"
                + "\nimport org.springframework.orm.ibatis.SqlMapClientTemplate;"
                + "\nimport " + modelFileName + ";";

        result += "\npublic class " + daoServiceClassName + " extends SqlMapClientTemplate implements " + serviceName + "{"
                + "\nprivate "+daoName+" ticDao;"
                + "\npublic "+daoServiceClassName+"(){};"
                + "\npublic "+daoServiceClassName+"("+daoName+" ticDao){"
                + "\nthis.ticDao = ticDao;"
                + "\n}"
                + "\n@Override"
                + "\npublic java.lang.Long insert(" + modelName + " object) throws SQLException"
                + "\n{"
                + "\n   return ticDao.insert(object);"
                + "\n}"
                + "\n@Override"
                + "\npublic int update(" + modelName + " object) throws Exception {"
                + "\n   return ticDao.update(object);"
                + "\n}"
                + "\n@Override"
                + "\npublic int delete(Long keyVal) throws Exception {"
                + "\n   return ticDao.delete(keyVal);"
                + "\n}"
                + "\n@Override"
                + "\npublic List selectAll" + tableInfo.getTableClassName() + "() throws Exception {"
                + "\n   return ticDao.selectAll"+ tableInfo.getTableClassName()+"();"
                + "\n}"
                + "\n@Override"
                + "\npublic " + modelName + " select" + tableInfo.getTableClassName() + "ByID(Long keyVal) throws Exception {"
                + "\n   return ticDao.select"+ tableInfo.getTableClassName() + "ByID(keyVal);"
                + "\n}"
                + "}";

        return result;
    }
    
    public static String MakeSQLMapFileFromTable(HVKTableInfo tableInfo) {
        if (tableInfo == null || tableInfo.name == null || tableInfo.name.trim().equals("")) {
            return "-0: Object table is null. Please check the object.";
        }
        HVKLogManager.WriteLogAcction("Begin create SQL map file for table :" + tableInfo.name + "...");
        String mess = "";
        if (HVKSetting.ibatisMapRootFolder.endsWith("\\") || HVKSetting.ibatisMapRootFolder.endsWith("/")) {
            HVKSetting.ibatisMapRootFolder = HVKSetting.ibatisMapRootFolder.substring(0, HVKSetting.ibatisMapRootFolder.length() - 1);
        }
//        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + "\\" + tableInfo.getTableClassName() + ".java";

        String fileName = tableInfo.getTableClassName().substring(0, 1).toLowerCase().concat(tableInfo.getTableClassName().substring(1, tableInfo.getTableClassName().length()));

        String filePath = HVKSetting.ibatisMapRootFolder.trim() + "\\" + fileName + ".xml";

        File fileToWrite = new File(filePath);
        if (fileToWrite.exists()) {
            HVKLogManager.WriteError("-1: File " + filePath + " existed. Can't not replacae file.", HVKBaseUtils.class.getName(), "MakeSQLMapFileFromTable");
            mess = "-1: File " + filePath + " existed. Can't not replacae file.";
        } else {
            String body = MakeSQLMapFromTable(tableInfo);
            try {
                WriteToFile(filePath, body);
                mess = "ok: File " + filePath + " created successful!";
            } catch (Exception ex) {
                HVKLogManager.WriteError(ex.getMessage(), HVKBaseUtils.class.getName(), "MakeSQLMapFileFromTable");
                mess = "-1: File " + filePath + " existed." + ex.getMessage();
            }
        }
        HVKLogManager.WriteLogAcction("Finished create SQL map file for table : " + tableInfo.name + " .Result : " + mess);
        return mess;
    }

    public static String MakeSQLMapFromTable(HVKTableInfo tableInfo) {

        String mapNameSpace = HVKSetting.prefixNamespaceXMLMap + tableInfo.getTableClassName();
//        String classModelMap = HVKSetting.modelMapRootPackage.trim().toLowerCase() + "." + tableInfo.getTableClassName().toLowerCase()+"."+tableInfo.getTableClassName();
        String classModelMap = HVKSetting.modelMapRootPackage.trim().toLowerCase() + "." + tableInfo.getTableClassName() + HVKSetting.suffixModel;
        String alias = tableInfo.getTableClassName() + HVKSetting.suffixXMLMapAlias;
        String tableTrimName = tableInfo.name.toLowerCase().replace("_", "");
        String resultMapName = tableTrimName + HVKSetting.suffixResultMap;

        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        result += "\n" + HVKSetting.spring_map_doctype;
        result += "\n<sqlMap namespace=\"" + mapNameSpace + "\">";
        result += "\n<typeAlias alias=\"" + alias + "\" type=\"" + classModelMap + "\"/>";
        result += "\n    <!--cacheModel id=\""+tableInfo.getTableClassNameLowerbegin()+"Cache\" type=\"MEMORY\" readOnly=\"false\" serialize=\"true\">\n" +
                "        <flushInterval hours=\"24\" minutes=\"0\" seconds=\"0\" milliseconds=\"0\"/>\n" +
                "        <flushOnExecute statement=\""+mapNameSpace+".update\"/>\n" +
                "        <flushOnExecute statement=\""+mapNameSpace+".insert\"/>\n" +
                "        <flushOnExecute statement=\""+mapNameSpace+".delete\"/>\n" +
                "       </cacheModel-->";
        result += "\n<resultMap id=\"" + resultMapName + "\" class=\"" + alias + "\">";
        for (HVKColumnInfo columnInfo : tableInfo.colums.values()) {
            result += "\n<result property=\"" + columnInfo.getFieldName() + "\" column=\"" + columnInfo.name + "\"/>";
        }
        result += "\n</resultMap>";
        result += HVKOracleDiscover.GetInsertSQLFromTable(tableInfo);
        result += HVKOracleDiscover.GetUpdateSQLFromTable(tableInfo);
        result += HVKOracleDiscover.GetDeleteSQLFromTable(tableInfo);
        result += HVKOracleDiscover.GetSelectAllSQLFromTable(tableInfo);
        result += HVKOracleDiscover.GetSelectByIDSQLFromTable(tableInfo);

        result += "\n</sqlMap>";
        return result;
    }

    public static ArrayList<String> MakeModeFilesFromListTable(ArrayList<HVKTableInfo> tables) {
        ArrayList<String> results = new ArrayList<String>();
        for (HVKTableInfo tableInfo : tables) {
            results.add(MakeModelFileFromTable(tableInfo));
        }
        return results;
    }

    public static String MakeModelFileFromTable(HVKTableInfo tableInfo) {
        if (tableInfo == null || tableInfo.name == null || tableInfo.name.trim().equals("")) {
            return "-0: Object table is null. Please check the object.";
        }
        HVKLogManager.WriteLogAcction("Begin create Model file for table :" + tableInfo.name + "...");
        String mess = "";
        if (HVKSetting.modelMapRootFolder.endsWith("\\") || HVKSetting.modelMapRootFolder.endsWith("/")) {
            HVKSetting.modelMapRootFolder = HVKSetting.modelMapRootFolder.substring(0, HVKSetting.modelMapRootFolder.length() - 1);
        }
//        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + "\\" + tableInfo.getTableClassName() + ".java";
        String filePath = HVKSetting.modelMapRootFolder.trim() + "\\" + tableInfo.getTableClassName() + HVKSetting.suffixModel + ".java";

        File fileToWrite = new File(filePath);
        if (fileToWrite.exists()) {
            HVKLogManager.WriteError("-1: File " + filePath + " existed. Can't not replacae file.", HVKBaseUtils.class.getName(), "MakeModelFileFromTable");
            mess = "-1: File " + filePath + " existed. Can't not replacae file.";
        } else {
            String body = MakeModelBodyFormTable(tableInfo);
            try {
                WriteToFile(filePath, body);
                mess = "ok: File " + filePath + " created successful!";
            } catch (Exception ex) {
                HVKLogManager.WriteError(ex.getMessage(), HVKBaseUtils.class.getName(), "MakeModelFileFromTable");
                mess = "-1: File " + filePath + " existed." + ex.getMessage();
            }
        }
        HVKLogManager.WriteLogAcction("Finished create Model file for table : " + tableInfo.name + " .Result : " + mess);
        return mess;
    }

    public static String MakeModelBodyFormTable(HVKTableInfo tableInfo) {
        String rfb = "package " + HVKSetting.modelMapRootPackage.trim().toLowerCase() + "; \n";

        rfb += GetAllImportsForClass(tableInfo);
        if (!rfb.contains("import java.io.Serializable")) {
            rfb += "\n import java.io.Serializable;";
        }
        rfb += "\npublic class " + tableInfo.getTableClassName() + HVKSetting.suffixModel + " implements Serializable {";
        for (HVKColumnInfo columnInfo : tableInfo.colums.values()) {
            rfb += GetDeclareFieldForColumn(columnInfo);
        }
        rfb += "}";//Close class
        return rfb;
    }

    private static String GetAllImportsForClass(HVKTableInfo tableInfo) {
        String result = "";
        for (HVKColumnInfo column : tableInfo.colums.values()) {
            String importType = GetImportClassForType(column.type);
            if (!importType.equalsIgnoreCase("-1")) {
                result += "\n import " + importType + ";";
            }
        }
        return result;
    }

    private static String GetImportClassForType(String pOracleType) {
        String javaType = ConvertTypeSqlVSJava(pOracleType, HVKSetting.oracle_java_type_mapped_file);
        if (javaType.equalsIgnoreCase("date")) {
            return "java.util.Date";
        }
        return "-1";
    }

    private static String GetDeclareFieldForColumn(HVKColumnInfo column) {
        String javaType = ConvertTypeSqlVSJava(column.type, HVKSetting.oracle_java_jdbc_type_mapped_file);
        String result = "\nprivate " + javaType + " " + column.getFieldName() + ";";
        result += GetGetMethodForField(column.name, javaType);
        result += GetSetMethodForField(column.name, javaType);
        return result;
    }

    private static String GetGetMethodForField(String fieldName, String javaType) {
        String fieldNameInMethod = getFieldName(fieldName);
        String fielString = fieldNameInMethod.substring(0, 1).toUpperCase().concat(fieldNameInMethod.substring(1, fieldNameInMethod.length()));
        return "\npublic " + javaType + " get" + fielString + "(){ return " + fieldNameInMethod + ";}";
    }

    private static String GetSetMethodForField(String fieldName, String javaType) {

        String fieldNameInMethod = getFieldName(fieldName);
        String fielString = fieldNameInMethod.substring(0, 1).toUpperCase().concat(fieldNameInMethod.substring(1, fieldNameInMethod.length()));
        return "\npublic void set" + fielString + "(" + javaType + " p" + fieldNameInMethod + "){ this." + fieldNameInMethod + " = p" + fieldNameInMethod + ";}";
    }

    public static String getFieldName(String columName) {
        String[] nameParts = columName.split("_");
        String result = "";
        for (String p : nameParts) {
            String pP = p.replace("_", "");
            pP = pP.toLowerCase();
            if (pP.length() >= 1) {
                pP = pP.substring(0, 1).toUpperCase() + pP.substring(1);
            }
            result += pP;
        }
        if (result.length() >= 1) {
            result = result.substring(0, 1).toLowerCase() + result.substring(1);
        }
        return result;
    }

    //==== Database tool =========================================
    public static void WriteToFile(String FilePath, String Body) throws IOException {
        File fi = new File(FilePath);
        if (!fi.exists()) {
            fi.createNewFile();
        }
        FileWriter FW = new FileWriter(FilePath);
        FW.write(Body);
        FW.close();
    }

    public static String GetFileContent(String filepath) throws IOException {
        File fi = new File(filepath);
        if (!fi.exists()) {
            fi.createNewFile();
        }
        FileReader freader = null;
        String body = "";
        BufferedReader breader = null;
        try {
            freader = new FileReader(filepath);
            breader = new BufferedReader(freader);
            try {
                freader = new FileReader(filepath);
                String s;
                while ((s = breader.readLine()) != null) {
                    body += "\n" + s;
                }
                return body;
            } catch (Exception ex) {
                ex.getMessage();
            }
        } catch (FileNotFoundException ex) {
            ex.getMessage();
        } finally {
            try {
                freader.close();
                breader.close();
            } catch (IOException ex) {
                ex.getMessage();
            }
        }
        return body;
    }

    public static void AppendStringToFile(String file, String Append) {
        try {
            File fi = new File(file);
            if (!fi.exists()) {
                fi.createNewFile();
            }


            FileWriter fstream = new FileWriter(file, true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("\n" + Append);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    //====== Get Connection by Type  =============================
    public static Connection getOracleConnection() throws ClassNotFoundException, SQLException {
        String driverName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName);
        return DriverManager.getConnection(HVKSetting.databaseConnectionString, HVKSetting.databaseUsername, HVKSetting.databasePassword);
    }

    public static Connection getSQLServerConnectionType1() throws Exception {
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);
        return DriverManager.getConnection(HVKSetting.databaseConnectionString);
    }

    public static Connection getSQLServerConnectionType4() throws Exception {
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);
        return DriverManager.getConnection(HVKSetting.databaseConnectionString, HVKSetting.databaseUsername, HVKSetting.databasePassword);
    }

    public static Connection GetMySQLConnection() throws Exception {
        Class.forName("org.gjt.mm.mysql.Driver");
        return DriverManager.getConnection(HVKSetting.databaseConnectionString, HVKSetting.databaseUsername, HVKSetting.databasePassword);
    }

    //================ Execute SQL ===============================================
    public static boolean ExecuteSQL(String sql, Connection conn) throws Exception {
        boolean Ok = true;
        Statement stmt = conn.createStatement();
        Ok = stmt.executeUpdate(sql) == 1 ? true : false;
        return Ok;
    }

    public static ResultSet ExecuteResultSet(String SQL, Connection conn) throws Exception {
        Statement Stm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        return Stm.executeQuery(SQL);
    }

    public static int ExecuteUpdateSQL(String pSql, Connection conn) throws Exception {
        int Ok = -1;
        Statement stmt = conn.createStatement();
        Ok = stmt.executeUpdate(pSql);
        return Ok;
    }

    public static ArrayList ExecuteQuerryArrayList(String pSQL, Connection conn) throws Exception {
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = stmt.executeQuery(pSQL);
        HVKResultSet2Array cv = new HVKResultSet2Array();
        return cv.getArrayListResult(rs);
    }
//==========================================

    public static String FormatSQLCommand(Object Value) {
        if (Value == null) {
            return "''";
        }
        String NumberType = "FloatIntegerIntDoubleLongShort";
        if (Value.getClass().getSimpleName().equalsIgnoreCase("Boolean")) {
            return Value.toString().equalsIgnoreCase("true") == true ? "1" : "0";
        }
        if (!NumberType.toLowerCase().contains(Value.getClass().getSimpleName().toLowerCase())) {
            if (Value.toString().contains("'")) {
                return "N'" + Value.toString().replace("'", "\"") + "'";
            }
            return "N'" + Value.toString() + "'";
        } else {
            return Value.toString();
        }

    }

    public static String FormatSQLCommand(Object Value, String objectType) {

        String NumberType = "FloatIntegerIntDoubleLongShort";
        if (Value == null && !NumberType.equalsIgnoreCase(objectType)) {
            return "''";
        }
        if (Value.getClass().getSimpleName().equalsIgnoreCase("Boolean")) {
            return Value.toString().equalsIgnoreCase("true") == true ? "1" : "0";
        }
        if (!NumberType.toLowerCase().contains(Value.getClass().getSimpleName().toLowerCase())) {
            if (Value.toString().contains("'")) {
                return "N'" + Value.toString().replace("'", "\"") + "'";
            }
            return "N'" + Value.toString() + "'";
        } else {
            return Value.toString();
        }

    }

    public static String ConvertTypeSqlVSJava(String sqlType, String fileTypeMap) {
        Properties propTypeMap = loadProperties(fileTypeMap);
        if (propTypeMap == null) {
            HVKLogManager.WriteError("ERROR : Please check the part of the file sql map : " + fileTypeMap, "HVKBaseUtil", "ConvertTypeSqlVSJava");
            return "ERROR : Please check the part of the file sql map : " + fileTypeMap;
        }
        return propTypeMap.getProperty(sqlType, "not found mapped type for type " + sqlType + " in file " + fileTypeMap);
    }

    public static Object ConvertToJavaObjectType(Object startO, String toType) throws Exception {
        if (startO == null) {
            return startO;
        }
        Object Ret = null;
        if ("boolean".contains(toType.toLowerCase())) {
            Ret = Boolean.valueOf(startO.toString().equalsIgnoreCase("1") == true ? "true" : "false");
        }
        if ("date".contains(toType.toLowerCase())) {
            if (startO.toString().toString().contains("-") && startO.toString().contains(":")) {
                Ret = java.sql.Date.valueOf(startO.toString().split(" ")[0]);
            }
        }
        if ("long".contains(toType.toLowerCase())) {
            Ret = Long.valueOf(startO.toString());
        }

        if ("float".contains(toType.toLowerCase())) {
            Ret = Float.valueOf(startO.toString());
        }
        if ("short".contains(toType.toLowerCase())) {
            Ret = Short.valueOf(startO.toString());
        }
        if ("image".contains(toType.toLowerCase())) {
            throw new Exception("Do not support type: java.awt.Image");
        }
        if ("integerint".contains(toType.toLowerCase())) {
            Ret = Integer.valueOf(startO.toString());
        }
        if (Ret == null) {
            Ret = startO;
        }
        return Ret;

    }

    public static Properties loadProperties(String fileProName) {
        Properties prop = new Properties();
        try {
            //load a properties file
            FileInputStream fis = new FileInputStream(fileProName);
            prop.load(fis);
            fis.close();
            return prop;
        } catch (IOException ex) {
            return null;
        }
    }

    public static boolean rewriteDatabaseConfigValue(Properties prop, String fileOut) {
        try {
            FileOutputStream fos = null;
            fos = new FileOutputStream(fileOut);
            prop.store(fos, null);
            return true;
        } catch (IOException ex) {
            Logger.getLogger(HVKBaseUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    public static void mergeProperties(String fileIn1, String fileIn2, String fileOut) {
        Properties propOut = loadProperties(fileIn1);
        Properties prop2 = loadProperties(fileIn2);
        Enumeration enumProps = prop2.propertyNames();
        while (enumProps.hasMoreElements()) {
            String key = (String) enumProps.nextElement();
            if (propOut.containsKey(key)) {
                alterProperties(propOut, key, prop2.getProperty(key));
            }
        }
        rewriteDatabaseConfigValue(propOut, fileOut);
    }

    private static Properties alterProperties(Properties prop, String keyToAlter, String valueToAlter) {
        Properties newProps = new Properties();
        Enumeration enumProps = prop.propertyNames();
        String key = "";
        boolean altered = false;
        while (enumProps.hasMoreElements()) {
            key = (String) enumProps.nextElement();
            if (key.equals(keyToAlter)) {
                newProps.setProperty(key, valueToAlter);
                altered = true;

            } else {
                newProps.setProperty(key, prop.getProperty(key));
            }
        }
        if (!altered) {
            newProps.setProperty(keyToAlter, valueToAlter);
        }
        return newProps;


    }
}
